<template>
  <div class="workstation-operation">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>工位进出站模拟</span>
        </div>
      </template>

      <!-- 操作区域 -->
      <div class="operation-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <div class="operation-header">
                  <el-icon><Position /></el-icon>
                  <span>工位进站</span>
                </div>
              </template>
              <el-form :model="inForm" label-width="100px">
                <el-form-item label="工位">
                  <el-select v-model="inForm.workstationId" placeholder="请选择空闲工位" style="width: 100%" clearable>
                    <el-option
                      v-for="station in idleWorkstations"
                      :key="station.id"
                      :label="station.name"
                      :value="Number(station.id)"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="工单号">
                  <el-select
                    v-model="inForm.workOrderCode"
                    placeholder="请选择工单号"
                    style="width: 100%"
                    filterable
                    clearable
                    @change="handleWorkOrderChange"
                  >
                    <el-option
                      v-for="order in availableWorkOrders"
                      :key="order.workOrderCode"
                      :label="order.workOrderCode"
                      :value="order.workOrderCode"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="产品">
                  <el-input :value="productIn" placeholder="请先选择工单号" readonly style="width: 100%"  disabled/>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="handleStationIn" :loading="inLoading">
                    <el-icon><Right /></el-icon>
                    进站
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <div class="operation-header">
                  <el-icon><Back /></el-icon>
                  <span>工位出站</span>
                </div>
              </template>
              <el-form :model="outForm" label-width="100px">
                <el-form-item label="工位">
                  <el-select v-model="outForm.workstationId" placeholder="请选择运行中工位" style="width: 100%">
                    <el-option
                      v-for="station in runningWorkstations"
                      :key="station.id"
                      :label="station.name"
                      :value="Number(station.id)"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="工单号">
                  <el-select
                    v-model="outForm.workOrderCode"
                    placeholder="请选择工单号"
                    style="width: 100%"
                    filterable
                    clearable
                    @change="handleOutWorkOrderChange"
                  >
                    <el-option
                      v-for="order in availableWorkOrders"
                      :key="order.workOrderCode"
                      :label="`${order.workOrderCode} - ${order.productName}`"
                      :value="order.workOrderCode"
                    >
                      <div class="work-order-option">
                        <div class="work-order-code">{{ order.workOrderCode }}</div>
                        <div class="product-name">{{ order.productName }}</div>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="产品">
                  <el-input :value="productOut" placeholder="请先选择工单号" readonly style="width: 100%" disabled />
                </el-form-item>

                <el-form-item>
                  <el-button type="success" @click="handleStationOut" :loading="outLoading">
                    <el-icon><Back /></el-icon>
                    出站
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 实时状态 -->
      <div class="status-section">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>实时工位状态</span>
              <el-button type="primary" size="small" @click="refreshStatus">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6" v-for="status in realTimeStatus" :key="status.workstationId">
              <el-card class="status-card" :class="getStatusClass(status.status)">
                <div class="status-content">
                  <div class="status-title">{{ status.workstationName }}</div>
                  <div class="status-info">
                    <div class="status-item">
                      <span class="label">状态:</span>
                      <el-tag :type="getStatusTagType(status.status)">{{ getStatusText(status.status) }}</el-tag>
                    </div>
                    <div class="status-item" v-if="status.serialNumber">
                      <span class="label">序列号:</span>
                      <span>{{ status.serialNumber }}</span>
                    </div>
                    <div class="status-item" v-if="status.currentWorkOrderCode">
                      <span class="label">工单号:</span>
                      <span>{{ status.currentWorkOrderCode }}</span>
                    </div>
                    <div class="status-item" v-if="status.operatorName">
                      <span class="label">操作员:</span>
                      <span>{{ status.operatorName }}</span>
                    </div>
                    <div class="status-item" v-if="status.runningDuration">
                      <span class="label">运行时长:</span>
                      <span>{{ status.runningDuration }}分钟</span>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 操作记录 -->
      <div class="records-section">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>操作记录</span>
              <el-button type="primary" size="small" @click="refreshRecords">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-table :data="operationRecords" stripe>
            <el-table-column prop="workstationName" label="工位" width="120" />
            <el-table-column prop="workOrderCode" label="工单号" width="120" />
            <el-table-column prop="serialNumber" label="序列号" width="150" />
            <el-table-column prop="productName" label="产品" width="100" />
            <el-table-column prop="operationType" label="操作类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.operationType === 'IN' ? 'success' : 'warning'">
                  {{ row.operationType === "IN" ? "进站" : "出站" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="operatorName" label="操作员" width="100" />
            <el-table-column prop="operationTime" label="操作时间" width="180" />
            <el-table-column prop="processingDuration" label="加工时长(分)" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'SUCCESS' ? 'success' : 'danger'">
                  {{ row.status === "SUCCESS" ? "成功" : "失败" }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="WorkstationOperation">
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { Position, Right, Back, Refresh, Box } from "@element-plus/icons-vue";
import {
  getAvailableWorkstationsForIn,
  getAvailableWorkstationsForOut,
  stationIn,
  stationOut,
  getRealTimeStatus,
  getOperationRecords,
  getAvailableWorkOrders,
  getAvailableSerialNumbers
} from "@/api/modules/workstation";

// 表单数据
const inForm = ref({
  workstationId: null as number | null,
  workOrderCode: "",
  serialNumber: ""
});

const outForm = ref({
  workstationId: null as number | null,
  workOrderCode: "",
  serialNumber: ""
});

// 加载状态
const inLoading = ref(false);
const outLoading = ref(false);

// 工位列表
const idleWorkstations = ref<Array<{ id: string; name: string; code: string }>>([]);
const runningWorkstations = ref<Array<{ id: string; name: string; code: string }>>([]);

// 工单号和序列号列表
const availableWorkOrders = ref<WorkOrderOption[]>([]);
const availableSerialNumbers = ref<SerialNumberOption[]>([]);

// 实时状态
const realTimeStatus = ref<WorkstationOperation.RuntimeStatus[]>([]);

// 操作记录
const operationRecords = ref<WorkstationOperation.OperationRecord[]>([]);

// 计算属性：选中的产品信息
const selectedProduct = computed(() => {
  if (!inForm.value.workOrderCode) return null;
  return availableWorkOrders.value.find(order => order.workOrderCode === inForm.value.workOrderCode);
});

const selectedOutProduct = computed(() => {
  if (!outForm.value.workOrderCode) return null;
  return availableWorkOrders.value.find(order => order.workOrderCode === outForm.value.workOrderCode);
});

// 工位进站
const handleStationIn = async () => {
  if (!inForm.value.workstationId || !inForm.value.workOrderCode) {
    ElMessage.warning("请选择工位和工单号");
    return;
  }

  inLoading.value = true;
  try {
    const { data } = await stationIn(inForm.value);
    ElMessage.success("进站成功");

    // 清空表单
    inForm.value = {
      workstationId: null,
      workOrderCode: "",
      serialNumber: ""
    };

    // 刷新状态和记录
    await Promise.all([refreshStatus(), refreshRecords(), loadWorkstationsByStatus()]);
  } catch (error) {
    ElMessage.error("进站失败");
  } finally {
    inLoading.value = false;
  }
};

// 工位出站
const handleStationOut = async () => {
  if (!outForm.value.workstationId || !outForm.value.workOrderCode || !outForm.value.serialNumber) {
    ElMessage.warning("请填写完整信息");
    return;
  }

  outLoading.value = true;
  try {
    const { data } = await stationOut(outForm.value);
    ElMessage.success("出站成功");

    // 清空表单
    outForm.value = {
      workstationId: null,
      workOrderCode: "",
      serialNumber: ""
    };

    // 刷新状态和记录
    await Promise.all([refreshStatus(), refreshRecords(), loadWorkstationsByStatus()]);
  } catch (error) {
    ElMessage.error("出站失败");
  } finally {
    outLoading.value = false;
  }
};

// 刷新实时状态
const refreshStatus = async () => {
  try {
    const { data } = await getRealTimeStatus();
    realTimeStatus.value = data;
  } catch (error) {
    console.error("获取实时状态失败:", error);
  }
};

// 刷新操作记录
const refreshRecords = async () => {
  try {
    const { data } = await getOperationRecords({});
    operationRecords.value = data;
  } catch (error) {
    console.error("获取操作记录失败:", error);
  }
};

// 加载工单号列表
const loadAvailableWorkOrders = async () => {
  try {
    const { data } = await getAvailableWorkOrders();
    availableWorkOrders.value = data;
  } catch (error) {
    console.error("获取工单号列表失败:", error);
  }
};

const productIn = ref("");

// 工单号变化处理
const handleWorkOrderChange = (workOrderCode: string) => {
  // 清空序列号
  inForm.value.serialNumber = "";

  if (!workOrderCode) {
    productIn.value = "";
    return;
  }

  const workOrder = availableWorkOrders.value.find(order => order.workOrderCode === workOrderCode);
  productIn.value = workOrder ? workOrder.productName : "";
};

const productOut = ref("");
// 出站工单号变化处理
const handleOutWorkOrderChange = (workOrderCode: string) => {
  // 清空序列号
  outForm.value.serialNumber = "";

  if (!workOrderCode) {
    // 如果清空工单号，也清空序列号列表
    availableSerialNumbers.value = [];
    return;
  }

  const workOrder = availableWorkOrders.value.find(order => order.workOrderCode === workOrderCode);
  productOut.value = workOrder ? workOrder.productName : "";
};

// 获取状态样式类
const getStatusClass = (status: string) => {
  switch (status) {
    case "IN_PROGRESS":
      return "status-running";
    case "IDLE":
      return "status-idle";
    case "COMPLETED":
      return "status-idle";
    case "FAULT":
      return "status-fault";
    default:
      return "status-normal";
  }
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case "IN_PROGRESS":
      return "success";
    case "IDLE":
      return "info";
    case "COMPLETED":
      return "success";
    case "FAULT":
      return "danger";
    default:
      return "warning";
  }
};

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "IN_PROGRESS":
      return "运行中";
    case "IDLE":
      return "空闲";
    case "COMPLETED":
      return "已完成";
    case "FAULT":
      return "故障";
    case "WAITING":
      return "等待中";
    default:
      return "未知";
  }
};

// 获取可用工位列表
const loadWorkstationsByStatus = async () => {
  try {
    // 获取可进站的工位
    const inResponse = await getAvailableWorkstationsForIn();
    idleWorkstations.value = inResponse.data.map(item => ({
      id: item.id,
      name: `${item.workstationName}(${item.workstationCode})`,
      code: item.workstationCode
    }));

    // 获取可出站的工位
    const outResponse = await getAvailableWorkstationsForOut();
    runningWorkstations.value = outResponse.data.map(item => ({
      id: item.id,
      name: `${item.workstationName}(${item.workstationCode})`,
      code: item.workstationCode
    }));
  } catch (error) {
    console.error("获取工位列表失败:", error);
    ElMessage.error("获取工位列表失败");
  }
};

onMounted(() => {
  loadWorkstationsByStatus();
  loadAvailableWorkOrders();
  refreshStatus();
  refreshRecords();
});
</script>

<style scoped lang="scss">
.workstation-operation {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .operation-section {
    margin-bottom: 20px;

    .operation-header {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .status-section {
    margin-bottom: 20px;

    .status-card {
      margin-bottom: 10px;
      border-radius: 8px;
      transition: all 0.3s;

      &.status-running {
        border-left: 4px solid #67c23a;
      }

      &.status-idle {
        border-left: 4px solid #909399;
      }

      &.status-fault {
        border-left: 4px solid #f56c6c;
      }

      &.status-normal {
        border-left: 4px solid #e6a23c;
      }

      .status-content {
        .status-title {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 10px;
        }

        .status-item {
          display: flex;
          align-items: center;
          margin-bottom: 5px;

          .label {
            font-weight: 500;
            margin-right: 8px;
            min-width: 60px;
          }
        }
      }
    }
  }

  .records-section {
    .el-table {
      margin-top: 10px;
    }
  }
}
</style>